<template>
  <div>
    <!-- <div class="tag-container box box-ac">
      发票类型：
      <div class="tag-list box box-f1">
        <div @click="changeTag(index,'billType')" v-for="(item, index) in billType.list" :class="{act:item.id==billType.checked}" class="animated tag-item box box-ac box-pc">{{item.name}}</div>
      </div>
    </div> -->
    <div class="tips-line">
      发票信息
    </div>
    <div class="box box-ver bill-detail">
      <div class="line-input box box-ac">
        <div class="title"><span>*</span>发票代码</div>
        <input v-model="invoicecode" @blur="checkCode" class="box box-ac box-f1" placeholder="请输入10或12位数字" type="tel">
      </div>
      <div class="line-input box box-ac">
        <div class="title"><span>*</span>发票号码</div>
        <input v-model="invoicenumber" @blur="checkCode" class="box box-ac box-f1" placeholder="请输入8位数字" type="tel">
      </div>
      <div class="line-input box box-ac">
        <div class="title"><span>*</span>开票日期</div>
        <!-- <div class="icon icon-date"></div> -->
        <input  @click="showPicker()" v-model="invoicedate" class="datePicker" type="text">
        <!-- <div  class="datePicker">{{invoicedate}}</div> -->
      </div>
      <!-- <div class="line-input box box-ac">
        <div><span>*</span>开票金额（不含税）：</div>
        <input v-model="invoiceamount" class="box box-ac box-f1" placeholder="请输入不含税金额" type="tel">
      </div> -->
      <div v-if="isjym && isjym != 1" class="line-input box box-ac">
        <div class="title"><span>*</span>开票金额</div>
        <input v-model="totalamount" class="box box-ac box-f1" placeholder="请输入不含税金额" type="number">
      </div>
      <div v-if="isjym == 1" class="line-input box box-ac">
        <div class="title"><span>*</span>校验码&nbsp;&nbsp;&nbsp;&nbsp;</div>
        <input v-model="totalamount" class="box box-ac box-f1" placeholder="请输入校验码后六位数字" type="tel">
      </div>
    </div>

    <code-tpl ref="codeTpl" @codeChange="changeBillType" :invoicecode="invoicecode" :invoicenumber="invoicenumber"></code-tpl>
    <div class="tips-line">
      <span>*</span>请选择报销类别
    </div>
    <div class="business-container box bor-none">
      <div @click="changeTag(index,'businessType')" v-for="(item, index) in businessType.list" :value="item" :key="index" :class="{act:index===businessType.checkedIndex}" class="item box box-f1 box-ac box-pc box-ver">
        <div :class="'icon-business'+(index+1)" class="icon animated"></div>
        <div class="text">{{item.name}}</div>
      </div>
    </div>
    <label v-if="!pdfuuid" class="box bill-img-add box-ac">
      <input @change="getFile($event)" id="checkPhoto" ref="file" type="file" accept="application/pdf">
      <div class="icon icon-addimg" for="checkPhoto"></div>
      <div class="text">上传pdf附件（没有可不传）</div>
    </label>
    <!-- <div @click="previewImage (index, checkedImg)" v-if="checkedImg.length > 0" v-for="(item, index) in checkedImg" class="billImg icon animated fadeIn" :style="{'background-image': 'url('+ item +')'}">
      <div @click.stop="clearBillImg()" class="icon icon-close"></div>
    </div> -->
    <div v-if="pdfuuid" class="box box-ac file-container bc-fff">
      <div class="icon icon-file"></div>
      <div class="box-f1">{{file.name}}</div>
      <div @click.stop="clearFile()" class="icon icon-close"></div>
    </div>
    <div class="h-bot"></div>
    <div class="btn-bot box w-p100">
      <div @click="checkInvoice(1)" class="box box-f1 box-pc box-ac w-p100">保存并继续添加</div>
      <div @click="checkInvoice(2)" class="box box-f1 box-pc box-ac w-p100 opposite">保存至发票夹</div>
    </div>
  </div>
</template>

<script>
import config from '@/js/config'
import { formatDate, formatMoney } from '../js/common'
import { openToast, popup } from '@/js/tools'
import Picker from '@/js/datePicker'
import '../css/dataPicker.scss'
import codeTpl from '@/components/codeTpl'
import { mapState } from 'vuex'
export default {
  components: {
    codeTpl
  },
  data () {
    return {
      detailList: [],
      checkedImg: '',
      code: {
        imagecontent: '',
        imagetype: ''
      },
      invoicecode: '',
      invoicenumber: '',
      invoiceamount: '', // 不含税金额
      totalamount: '', // 校验码后六位
      invoicedate: '请选择开票日期',
      file: {},
      pdfuuid: '',
      isjym: null, // 1-普票 输入校验码后六位 0-不含税金额
      invoiceresult: null,
      businessType: {
        checkedIndex: '',
        list: [{
          name: '住宿费',
          id: 1
        }, {
          name: '餐饮费',
          id: 2
        }, {
          name: '通讯费',
          id: 3
        }, {
          name: '其他',
          id: 4
        }]
      },
      billType: {
        checked: 1,
        list: [{
          name: '专票',
          id: 0
        }, {
          name: '普票',
          id: 1
        }]
      }
    }
  },
  computed: {
    ...mapState(['userNum'])
  },
  beforeRouteLeave (to, from, next) {
    let datePicker = document.querySelector('.zx_mask')
    if (datePicker) datePicker.remove()
    next()
  },
  mounted () {
    // this.getCodeImg()
  },
  methods: {
    checkCode () {
      let invoicecode = this.invoicecode
      let invoicenumber = this.invoicenumber
      if ((invoicecode.length === 10 || invoicecode.length === 12) && invoicenumber.length === 8) {
        this.$refs.codeTpl.getCode()
      }
    },
    /**
     *
    */
    checkInvoice (type) {
      let _this = this
      let checkkey = this.$store.state.checkkey
      let invoicecode = _this.invoicecode
      let invoicenumber = _this.invoicenumber
      let invoicedate = _this.invoicedate.replace(/-/g, '')
      let totalamount = _this.totalamount
      // 验证码
      let $codeTpl = _this.$refs.codeTpl
      let imagecode = $codeTpl.imagecode
      let yzmsj = $codeTpl.yzmsj
      let ymmj = $codeTpl.ymmj
      if (!_this.businessType.checkedIndex && _this.businessType.checkedIndex !== 0) {
        openToast({
          msg: '请选择报销类别',
          duration: 2000
        })
        return
      }
      let detailedtype = _this.businessType.list[_this.businessType.checkedIndex].id
      if (invoicecode.length !== 10 && invoicecode.length !== 12) {
        openToast({
          msg: '发票代码为10或12位数字',
          duration: 2000
        })
        return
      }
      if (invoicenumber.length !== 8) {
        openToast({
          msg: '发票号码为8位数字',
          duration: 2000
        })
        return
      }
      if (_this.invoicedate.split('-').length !== 3) {
        openToast({
          msg: '请选择开票日期',
          duration: 2000
        })
        return
      }
      if (!_this.isjym) {
        openToast({
          msg: '请先获取验证码',
          duration: 2000
        })
        return
      }
      if (+_this.isjym === 1) {
        if (!_this.totalamount) {
          openToast({
            msg: '请填写校验码后六位',
            duration: 2000
          })
          return
        }
      } else {
        if (!_this.totalamount) {
          openToast({
            msg: '请填写不含税金额',
            duration: 2000
          })
          return
        }
      }
      if (!_this.$refs.codeTpl.imagecode) {
        openToast({
          msg: '请填写验证码',
          duration: 2000
        })
        return
      }
      _this.$http({
        $vue: _this,
        type: 'XML',
        method: 'post',
        url: config.GXUrl + '/CheckInvoice/services/AutoImageCenter.ws?wsdl',
        data: {
          servername: 'CheckInvoice',
          data: {
            checkkey: checkkey,
            checktype: '4',
            invoicecode,
            invoicenumber,
            totalamount,
            imagecode,
            invoicedate,
            yzmsj,
            ymmj
          }
        }
      }).then(item => {
        if (+item.result['#text'] === 0) {
          _this.invoiceresult = JSON.parse(item.invoiceresult['#text'])
          _this.saveInvoice(type)
        }
      })
    },
    saveInvoice (type) {
      let _this = this
      let datasource = 6
      // 发票类型
      let detailedtype = _this.businessType.list[_this.businessType.checkedIndex].id
      // 不含税金额
      _this.invoiceamount = _this.invoiceresult.jamount
      // 总金额
      let totalamount = _this.invoiceresult.totalamount
      _this.$http({
        $vue: _this,
        type: 'XML',
        method: 'post',
        url: config.GXUrl + '/CheckInvoice/services/AutoImageCenter.ws?wsdl',
        data: {
          servername: 'saveInvoice',
          data: {
            useraccount: this.userNum,
            invoicecode: _this.invoicecode,
            invoicenum: _this.invoicenumber,
            invoicedate: _this.invoicedate,
            invoiceamount: _this.invoiceamount,
            totalamount: totalamount,
            detailedtype,
            datasource,
            pdfuuid: _this.pdfuuid,
            checkresult: 1,
            gfnsrsbh: _this.invoiceresult.inaccount,
            gfname: _this.invoiceresult.inname,
            xfnsrsbh: _this.invoiceresult.outaccount,
            xfname: _this.invoiceresult.outname,
            tnvoicetype: _this.invoiceresult.fplx,
            machinecode: _this.invoiceresult.fpjqm,
            fpjym: _this.invoiceresult.fpjym,
            filepath: '',
            invoicekey: ''
          }
        }
      }).then(item => {
        if (+item.result['#text'] === 0) {
          if (type === 2) {
            _this.$router.replace('/myInvoice')
          } else {
            location.reload()
          }
        }
      })
    },
    showPicker () {
      let _this = this
      let picker = new Picker({
        type: '3', // 0-年, 1-年月, 2-月日, 3-年月日
        title: '请选择日期', // 标题（可选）
        maxYear: 2030, // 最大年份（可选）
        minYear: 2010, // 最小年份（可选）
        separator: '-', // 日期分割符(可选)
        defaultValue: '', // 默认值（可选）
        callBack: function (val) {
          _this.invoicedate = val
        }
      })
    },
    clearFile () {
      this.pdfuuid = ''
    },
    getFile (event) {
      let file = event.target.files[0]
      let _this = this
      // _this.file = file
      // _this.pdfuuid = 'xxx'
      this.invoiceHttpUpload(file)
    },
    previewImage (index, AimgUrl) {
      let _this = this
      wx.previewImage({
        current: AimgUrl[index], // 当前显示图片的http链接
        urls: AimgUrl // 需要预览的图片http链接列表
      })
    },

    changeBillType (isjym) {
      this.isjym = isjym
    },
    changeTag (index, data) {
      this[data].checkedIndex = index
    },
    invoiceHttpUpload (file) {
      // console.log(file)
      if (file.type !== 'application/pdf') {
        openToast({
          msg: '只支持上传pdf格式的附件',
          duration: 2000
        })
        return
      }
      this.$http({
        $vue: this,
        type: 'file',
        method: 'post',
        url: config.GXUrl + '/CheckInvoice/upload/invoiceHttpUpload.do',
        data: {
          useraccount: this.userNum,
          myFile: file
        }
      }).then(res => {
        // console.log(res)
        if (res.status === 0) {
          this.file = file
          this.pdfuuid = res.invoice[0].pdfuuid
        } else {
          openToast({
            msg: res.errormsg,
            duration: 2000
          })
        }
        // _this.pdfuuid = 111
      })
    },
    formatMoney (key) {
      this[key] = formatMoney(this[key])
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../css/color';
@import '../css/mixins';

.bill-detail .line-input:last-child{
  border:none
}
.datePicker{
  // margin-left:.1rem;
  // color:#999
}
.bill-img-add{
  background-color:#FFF;
  padding:.2rem .4rem;
  border-top:1px solid $borderColor;
  color:#999;
  #checkPhoto{
    display: none
  }
  .icon-addimg{
    margin-right:.3rem;
    width:1.04rem;
    height: 1.04rem;
    @include bg-image('../img/icon-addimg');
  }
}
.file-container{
  padding:.3rem;
  color:#666;
  border-top:1px solid $borderColor;
  .icon{
    width:.41rem;
    height:.41rem;
  }
  .icon-file{
    margin-right:.3rem;
    @include bg-image('../img/icon-file')
  }
  .icon-close{
    @include bg-image('../img/icon-close')
  }
}
// .billImg{
//   position: relative;
//   border-radius:.2rem;
//   width:6rem;
//   height: 3rem;
//   margin: .25rem auto;
//   @include bg-size(cover);
//   .icon-close{
//     position: absolute;
//     top:.1rem;
//     right:.1rem;
//     width:.41rem;
//     height:.41rem;
//     @include bg-image('../img/icon-close')
//   }
// }

</style>
